//: [Previous](@previous)

import Foundation

var str = "Strings and Characters"

// 字符串
let greeting = "Hello!" // 自动推断为String 类型
let chr1: Character = "中" // 字符类型
let chr2 = "Z" // 自动推断为String类型

//以下声明无效 invalid - multiple grapheme clusters
//let chr3: Character = "ABC"

// 字符串插值
let num1 = 10
let num2 = "\(num1)"
let num3 = "\(10+10)"
let sum = "num2 + num3 =  \(Int(num2)!+Int(num3)!)"
print(sum)

//字符串拼接
var str1 = "Hello"
var str2 = "World"
var str3 = str1 + " " + str2
print(str3)   // 输出：Hello World
str3 += " !"
print(str3)  //输出： Hello World !

str1.append(" Swift")
print(str1) // 输出：Hello Swift

var strArr = ["Hello","Swift"]
var str4 = strArr.joined()
print(str4) // 输出：HelloSwift
var str5 = strArr.joined(separator: "-")
print(str5)  //输出：Hello-Swift

// 字符串比较
// 判断是否为空
if str5.isEmpty  {
	print("st5 is Empty")
}else {
	print("st5 is not Empty")
}
// 输出：st5 is not Empty

let result = str5.isEmpty ? "str5 is empty" : str5
print(result) // 输出：Hello-Swift

"abc" == "abc"
"abc" == "ABC"
"abc" == "efg"
// true
// false
// false

//字符串字符遍历
for character in "Swift" {
	print(character)
}
//S
//w
//i
//f
//t


//分割字符串为数组
let strToArr = "hello swift"
let afterStrToStr1 = strToArr.components(separatedBy: " ")
//["hello", "swift"]
print(afterStrToStr1)

//字符串转换为数字类型
Int("100") // 100
Int("abc") // nil,若无法转换，则返回nil



//字符统计和索引
print("Hello Swift".count)  // 11

let startIndex = "Hello".startIndex
let endIndex = "Hello".endIndex
//Hello's startIndex:Index(_rawBits: 1),and endIndex Index(_rawBits: 327681)
print("Hello's startIndex:\(startIndex),and endIndex \(endIndex)")
print("Hello"[startIndex]) // H

//使用 indices属性来访问字符串中每个字符的索引。
for index in "Hello".indices {
	  //H e l l o
    print("\("Hello"[index]) ", terminator: "")
}

// 插入和删除

var welcome = "hello"
welcome.insert("!", at: welcome.endIndex)
// welcome now equals "hello!"
 
welcome.insert(contentsOf: " there", at: welcome.index(before: welcome.endIndex))
// welcome now equals "hello there!"

welcome.remove(at: welcome.index(before: welcome.endIndex))
// welcome now equals "hello there"
 
let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex
welcome.removeSubrange(range)
// welcome now equals "hello"


// 前缀和后缀
"hello world".hasPrefix("hello") // true
"hello world".hasSuffix("world") // true

// 字符串翻转，字符串本质就是字符的数组，可以直接调用reversed() 方法
let strA = "tfiws olleh"
var reversedStr = String(strA.reversed())
print(reversedStr)  // 输出：hello swift


let strWithSpace = " Hello Swift \n"
// 删除空白字符和换行
print(strWithSpace.trimmingCharacters(in: .whitespacesAndNewlines))
//删除空白字符
print(strWithSpace.trimmingCharacters(in: .whitespaces))
//删除换行字符
print(strWithSpace.trimmingCharacters(in: .newlines))


//大小写转换
let abcd = "heLLo Swift"
let uppercaseStr = abcd.uppercased() // "HELLO SWIFT"
let lowercaseStr = abcd.lowercased() // "hello swift"
let capitalizedStr = abcd.capitalized  //Hello Swift

//: [Next](@next)

